package com.yuanqi.WebSocket;

import cn.hutool.json.JSONUtil;
import com.yuanqi.Common.Pojo.Vo.ChatVo;
import com.yuanqi.Common.Pojo.entity.Chat;
import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chat")
@Component
public class MyWebSocket {

    private static ThreadLocalConfig threadLocalConfig;

    //  这里使用静态，让 service 属于类
    private static UserMapper userMapper;

    private  static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        MyWebSocket.stringRedisTemplate = stringRedisTemplate;
    }
    // 注入的时候，给类的 service 注入
    @Autowired
    public void setChatService(UserMapper userMapper) {
        MyWebSocket.userMapper = userMapper;
    }
    @Autowired
    public void setThreadLocalConfig(ThreadLocalConfig threadLocalConfig) {
        MyWebSocket.threadLocalConfig = threadLocalConfig;
    }

    public static final Map<String,Session> map = new ConcurrentHashMap<>();



    @OnOpen
    public void onOpen(Session session){
        String id = session.getId();
        map.put(id,session);
        ChatVo chatVo = new ChatVo();
        chatVo.setData(id);
        chatVo.setType("bind");
        session.getAsyncRemote().sendText(JSONUtil.toJsonStr(chatVo));
    }


    @OnClose
    public void onClose(Session session) throws IOException {
      if (session != null) {
          // 关闭会话的逻辑
          session.close();
          map.remove(session.getId());
      }
    }

    public static  Boolean sendMsg(Chat chat){
        String toId = chat.getToId().toString();
        String clientId = stringRedisTemplate.opsForValue().get(toId+"WebSocket");
        if(clientId!=null){
            chat.setTime(System.currentTimeMillis()/1000);
            String msg = JSONUtil.toJsonStr(chat);
            Session session = map.get(clientId);
            //说明用户下线了
            if (session==null)
            {
                return false;
            }
            session.getAsyncRemote().sendText(msg);
            return true;
        }
        else {
            return false;
        }
    }
}
